package lt.egidijus.aatest.wizards.helpers;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import lt.egidijus.aatest.cache.CacheableOption;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

public abstract class ATGDialog extends Dialog {

	protected CacheableOption option;

	/**
	 * InputDialog constructor
	 * 
	 * @param parent
	 *            the parent
	 */
	public ATGDialog(Shell parent, String name, CacheableOption option) {
		// Pass the default styles here
		this(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL, name);
		this.option = option;
	}

	/**
	 * InputDialog constructor
	 * 
	 * @param parent
	 *            the parent
	 * @param style
	 *            the style
	 */
	public ATGDialog(Shell parent, int style, String name) {
		// Let users override the default styles
		super(parent, style);
		setText("Configuration of " + name);

	}

	/**
	 * Opens the dialog and returns the input
	 * 
	 * @return String
	 */
	public String open() {
		// Create the dialog window
		Shell shell = new Shell(getParent(), getStyle());
		shell.setText(getText());
		createContents(shell);
		shell.pack();
		shell.open();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		// Return the entered value, or null
		return null;
	}

	public final List<String> keys = new ArrayList<String>(0);
	public final List<String> removeKeys = new ArrayList<String>(0);

	public abstract void createContents(final Shell shell);

	protected void updateTable(Table table, String[] titles,
			Map<String, String> cache, Label label) {
		label.setText("Total elements in cache " + option.getCache().size());
		label.redraw();
		keys.clear();
		removeKeys.clear();
		table.removeAll();
		int j = 1;
		for (String key : cache.keySet()) {
			TableItem rulesItem = new TableItem(table, SWT.NONE);
			rulesItem.setText(0, j + "");
			j++;
			rulesItem.setText(1, key);
			rulesItem.setText(2, cache.get(key));
			keys.add(key);
		}
		for (int i = 0; i < titles.length; i++) {
			table.getColumn(i).pack();
		}
	}

	public boolean isSucccess() {
		return true;
	}
}